﻿using King.Engine.Components;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace BreacherCreature.Components
{
    public delegate void EndTimerCallback();

    public class Timer : Component
    {
        EndTimerCallback _callback;

        public float MaxSeconds;
        public float CurSeconds;
        public bool Running;
        public bool Finished
        {
            get { return !Running && CurSeconds <= 0; }
        }
        public bool Paused
        {
            get { return !Running && CurSeconds >= 0; }
        }
        public float PercentRemaining
        {
            get {
                float remain = CurSeconds / MaxSeconds;
                if (remain < 0) remain = 0;
                if (remain > 1) remain = 1;
                return remain;
            }
        }

        public Timer(float maxSeconds, EndTimerCallback callback, bool start)
        {
            MaxSeconds = CurSeconds = maxSeconds;
            _callback = callback;

            Running = start;
        }
        public Timer(float maxSeconds, EndTimerCallback callback) : this(maxSeconds, callback, true) { }

        public override void Update(GameTime gameTime)
        {
            if (Running)
            {
                CurSeconds -= (float)gameTime.ElapsedGameTime.TotalSeconds;
                if (CurSeconds <= 0)
                {
                    Running = false;
                    _callback.Invoke();
                }
            }            
        }

        public void Reset(bool start)
        {
            CurSeconds = MaxSeconds;
            Running = start;
        }
        public void Reset() { Reset(true); }
    }
}
